package com.srwl.mytx.widget;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.RotateAnimation;

import androidx.fragment.app.FragmentActivity;

import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.activity.LoginActivity;
import com.srwl.mytx.domain.Coupon;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.fragment.RedPacketDialogFragment;
import com.srwl.mytx.fragment.SendMultiplePacketDialog;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.activity.MultipleCouponDetailActivity;
import com.srwl.mytx.utils.Utils;

/**
 * 一对多红包
 */
public class MultipleCouponView extends androidx.appcompat.widget.AppCompatImageView {
    private static final String TAG = "MultipleCouponView";
    private Coupon coupon;
    private boolean isChildCoupon;
    private boolean isMyCoupon;
    private Context context;
    private String liveRoomId;
    private String topicId;
    private InteractionListener listener;

    public MultipleCouponView(Context context) {
        super(context);
        this.context = context;
    }

    public MultipleCouponView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    public MultipleCouponView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
    }

    public void init(LiveRoom liveRoom) {
        liveRoomId = liveRoom.getId();
        coupon = liveRoom.getCoupon();
        init();
    }

    public void init(Topic topic) {
        topicId = topic.getId();
        this.coupon = topic.getCoupon();
        if (coupon != null) {
            coupon.setTargetUser(topic.getManager());
        }
        init();
    }

    public void init() {


        setVisibility(View.VISIBLE);
        setClickListener();
        if (coupon == null) {
            setImageResource(R.drawable.tx_live_red_packet_open);
            //为空，晃动，提醒可以发红包了
            //setAnimation(shakeAnimation(10));

        } else {

            if (coupon.getTargetUser() == null) {
                Log.e(TAG, "init: targetUser 红包发送者 不能为空");
            }
            checkIsChildCoupon();
            checkIsMyCoupon(coupon);
            if (coupon.getStatus() != null && coupon.getStatus() == Constant.COUPON_STATUS_RECEIVED) {
                setImageResource(R.drawable.tx_live_red_packet_open);
            } else {
                setAnimation(shakeAnimation(3));

            }
        }
    }

    /**
     * 当收到红包
     *
     * @param coupon
     */
    public void receiveCoupon(Coupon coupon) {
        this.coupon = coupon;
        if (coupon.getTargetUser() == null) {
            throw new RuntimeException("targetUser 红包发送者 不能为空");
        }
        checkIsMyCoupon(coupon);
        setImageResource(R.drawable.tx_live_red_packet);
        setAnimation(shakeAnimation(3));
        if (!isShown()) {
            setVisibility(VISIBLE);
        }

    }

    private void checkIsMyCoupon(Coupon coupon) {
        isMyCoupon = TextUtils.equals(coupon.getuId(), UserProfileManager.getInstance().getLoginUserInfo().getuId());
    }

    private void checkIsChildCoupon() {

        isChildCoupon = coupon.getType() == Constant.COUPON_TYPE_CHILD_RANDOM || coupon.getType() == Constant.COUPON_TYPE_CHILD_AVERAGE;

    }


    private void setClickListener() {
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getAnimation() != null) {
                    clearAnimation();
                }

                if (coupon == null) {
                    if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
                        getContext().startActivity(new Intent(getContext(), LoginActivity.class).putExtra("EXTRA_CONTENT", "发红包需要先登录"));
                        return;
                    }
                    showSendCouponDialog();

                } else {
                    if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
                        getContext().startActivity(new Intent(getContext(), LoginActivity.class).putExtra("EXTRA_CONTENT", "领红包需要先登录"));
                        return;
                    }
                    if (isChildCoupon) {//如果红包是子红包
                        showReceived();
                    } else {
                        //红包不为空，
                        if (isMyCoupon) {//是自己发送的红包，直接进入红包详情
                            showCouponDetail();
                        } else {   // 弹出领取红包对话框
                            showReceiveCoupon();
                        }
                    }
                }

            }
        });

    }

    private void showSendCouponDialog() {

        //红包为空，弹出发红包对话框
        SendMultiplePacketDialog sendMultiplePacketFragment = SendMultiplePacketDialog.newInstance(liveRoomId, topicId);
        sendMultiplePacketFragment.show(((FragmentActivity) context).getSupportFragmentManager(), "");
        sendMultiplePacketFragment.setListener(new SendMultiplePacketDialog.InteractionListener() {
            @Override
            public void onSendCouponSuccess(Coupon coupon) {
                setImageResource(R.drawable.tx_live_red_packet);
                isMyCoupon = true;
                coupon.setTargetUser(UserProfileManager.getInstance().getLoginUserInfo());
                MultipleCouponView.this.coupon = coupon;
                MultipleCouponView.this.showToast("发送红包完成");
                if (listener != null) {
                    listener.onSendCouponComplete(coupon);
                }
            }

            @Override
            public void showToast(String message) {

            }
        });

    }

    private void showCouponDetail() {

        Intent intent = new Intent(context, MultipleCouponDetailActivity.class);
        intent.putExtra(Constant.EXTRA_INFO_COUPON, coupon);
        context.startActivity(intent);

    }

    private void showReceiveCoupon() {

        RedPacketDialogFragment redPacketDialogFragment = RedPacketDialogFragment.newInstance(coupon);
        redPacketDialogFragment.show(((FragmentActivity) context).getSupportFragmentManager(), "RedPacketDialogFragment");
        redPacketDialogFragment.setOnFragmentInteractionListener(new RedPacketDialogFragment.OnFragmentInteractionListener() {
            @Override
            public void onReceiveCouponComplete(Coupon childCoupon, boolean isEmpty) {
                isChildCoupon = true;
                setImageResource(R.drawable.tx_live_red_packet_open);
                coupon = childCoupon;//接收成功返回的是 子红包
                if (listener != null) {
                    listener.onReceiveCouponComplete(coupon);
                }
            }

            @Override
            public void onStatusChange(Integer status) {
                coupon.setStatus(status);
                checkIsChildCoupon();
                if (coupon.getStatus() != null && coupon.getStatus() == Constant.COUPON_STATUS_RECEIVED) {
                    setImageResource(R.drawable.tx_live_red_packet_open);
                }
                if (listener != null) {
                    listener.onCouponStatusChange(coupon);
                }
            }

            @Override
            public void onCouponExpire(Coupon coupon) {

            }
        });

    }


    private void showReceived() {
        Intent intent = new Intent(context, MultipleCouponDetailActivity.class);
        intent.putExtra(Constant.EXTRA_INFO_CHILD_COUPON, coupon);
        context.startActivity(intent);
    }

    private void showToast(String content) {

        Snackbar.make(this, content, Snackbar.LENGTH_LONG).show();
    }

    /**
     * 晃动动画
     *
     * @param counts
     * @return
     */
    public static Animation shakeAnimation(int counts) {
        Animation rotateAnimation = new RotateAnimation(0, 20, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.75f);
        rotateAnimation.setInterpolator(new CycleInterpolator(6));//3000毫秒 时间内执行7次
        rotateAnimation.setRepeatCount(counts);
        rotateAnimation.setDuration(3000);
        return rotateAnimation;
    }

    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }

    public interface InteractionListener {

        void onSendCouponComplete(Coupon coupon);

        void onReceiveCouponComplete(Coupon coupon);

        void onCouponStatusChange(Coupon coupon);
    }


    //    private void getCouponStatus() {
//
//        RetrofitManager.getInstance().createRequest(CouponService.class)
//                .getCouponStatus(coupon.getId())
//                .enqueue(new Callback<CommonResult>() {
//                    @Override
//                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
//
//                        CommonResult result = response.body();
//                        if (!response.isSuccessful() || result == null || result.isError() | result.getData() == null) {
//                            showRedPacketView();
//                            return;
//                        }
//                        JSONObject body = (JSONObject) result.getData();
//                        coupon = body.toJavaObject(Coupon.class);
//                        showRedPacketView();
//                    }
//
//                    @Override
//                    public void onFailure(Call<CommonResult> call, Throwable t) {
//                        Log.e(TAG, "onFailure: " + t.getMessage());
//                        showRedPacketView();
//                    }
//                });
//
//    }

}
